<template>
  <el-card class="m-8">

    <section>

      <section slot="header" class="mb-4 flex items-center">
        <el-button class="mr-4" type="primary" @click="handleAdd()">新增</el-button>
      </section>


      <el-table :data="tableList" align="center" border class="mt-4" stripe style="width: 100%">
        <el-table-column label="奖励ID" prop="id"/>
        <el-table-column label="奖励名称" prop="title"/>
        <el-table-column label="奖励类型" prop="reward_type">
          <template slot-scope="{row}">
            {{ row.reward_type === 'debris' ? '碎片' : row.reward_type === 'gift' ? '礼物' : '装扮' }}
          </template>
        </el-table-column>
        <el-table-column label="奖励图片" prop="icon">
          <template slot-scope="{row}">
            <el-image :src="row.icon" fit="fill" style="width: 200px;" :lazy="true"></el-image>
          </template>
        </el-table-column>
        <el-table-column label="奖励有效期" prop="count">
          <template slot-scope="{row}">
            {{ row.reward_type === 'product' ? row.count + '天' : '--' }}
          </template>
        </el-table-column>
        <el-table-column label="奖励价值" prop="price">
          <template slot-scope="{row}">
            {{ row.reward_type === 'gift' ? row.price : '--' }}
          </template>
        </el-table-column>
        <el-table-column label="添加时间" prop="created_at"/>
        <el-table-column align="center" fixed="right" label="操作">
          <template slot-scope="{row}">
            <el-button :loading="detailLoading" plain type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" plain @click="handleSDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <cus-pagination
        :limit.sync="listQuery.perPage"
        :page.sync="listQuery.page"
        :total="meta.total"
        @pagination="initData"
      />
    </section>
    <el-dialog
      :visible.sync="dialogFormVisible"
      :title="dialogTitle"
      @close="handleCloseDialog('form')"
      width="30%"
    >
      <el-form
        ref="form"
        :model="formData"
        :rules="Rules"
        label-position="right"
        label-width="120px"
      >

      <el-form-item v-if="!isEdit" label="奖励类型" prop="reward_type">
          <el-select v-model="formData.reward_type" clearable filterable placeholder="请选择受限类型" @change="handleChange">
            <el-option
              v-for="item in rewardType"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item v-if="formData.reward_type === 'gift'" :label="isEdit?'选择替换礼物':'选择礼物'" prop="reward_id">
          <el-select v-model="formData.reward_id" remote clearable filterable :remote-method="remoteMethod" placeholder="请选择礼物" @clear="clear">
            <el-option
              v-for="item in menuList1"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
              <el-popover placement="right" trigger="hover">
                <img :src="item.picture" alt="" style="max-width: 200px;max-height: 200px">
                <p slot="reference">{{ item.name }}</p>
              </el-popover>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item v-if="formData.reward_type === 'product'" :label="isEdit?'选择替换奖励':'选择奖励'" prop="reward_id">
          <el-select v-model="formData.reward_id" remote clearable filterable :remote-method="remoteMethod2" placeholder="请选择奖励" @clear="clear2">
            <el-option
              v-for="item in menuList2"
              :key="item.id"
              :label="item.product_name"
              :value="item.id"
            >
              <el-popover placement="right" trigger="hover">
                <img :src="item.picture" alt="" style="max-width: 200px;max-height: 200px">
                <p slot="reference">{{ item.product_name }}</p>
              </el-popover>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="formData.reward_type === 'debris'" :label="isEdit?'选择替换碎片':'选择碎片'" prop="reward_id">
          <el-select v-model="formData.reward_id" remote clearable filterable placeholder="请选择碎片">
            <el-option
              v-for="item in menuList3"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
              <el-popover placement="right" trigger="hover">
                <img :src="item.icon" alt="" style="max-width: 200px;max-height: 200px">
                <p slot="reference">{{ item.name }}</p>
              </el-popover>
            </el-option>
          </el-select>
        </el-form-item>
        

        <el-form-item v-if="formData.reward_type=== 'product'" label="奖励有效期" prop="count">
          <el-input type="number" v-model="formData.count" @input="handleInput">
            <template slot="append">天</template>
          </el-input>
        </el-form-item>
      </el-form>
      <p style="color: red;" v-if="isEdit && formData.reward_type=== 'gift'">请使用等价值的礼物替换</p>
      <footer slot="footer">
        <el-button type="danger" @click="dialogFormVisible = false">取消</el-button>
        <el-button type="success" @click="handleOnSubmit">保存</el-button>
      </footer>
    </el-dialog>

  </el-card>
</template>

<script>
import { listData, prizeDeleted, prizeAdd, prizeEdit, productList, chipList } from '../../api/sunGame/sunGame'
// 礼物下拉数据
import { getData } from '@/api/roomGift/giftList'

export default {
  data() {
    return {
      dialogEditVisible: false,
      hasGame: false,
      options: [
        { val: 0, name: '禁用' },
        { val: 1, name: '正常' }
      ],
      room_name: {},
      room_options: [],
      title: '新增',
      listQuery: {
        page: 1,
        perPage: 10
      },
      cateList: [],
      templateList: [],
      formData: {
        reward_type: undefined,
        reward_id: undefined,
        count: undefined,
        level: undefined,
        is_open: undefined,
        id: undefined,
      },
      Rules: {
        reward_type: [{ required: true, message: '请选择奖励类型', trigger: 'blur' }],
        reward_id: [{ required: true, message: '请选择奖励', trigger: 'blur' }],
        level: [{ required: true, message: '请输入奖励等级', trigger: 'blur' }],
        count: [{ required: true, message: '请输入奖励有效期', trigger: 'blur' }],
      },
      RulesEdit: {
        reward_id: [{ required: true, message: '请选择礼物', trigger: 'change' }]
      },
      tableList: [],
      typeList: [],
      dataForm: {
        reward_id: undefined
      },
      meta: {
        page: 1,
        perPage: 10,
        total: 0
      },

      /* 弹出框开关 */
      dialogFormVisible: false,

      detailLoading: false,
      detail: {},
      rowId: '',
      sysInstanceTotalPages: 10,
      isEdit: false,
      rewardType: [
        {
          value: 'gift',
          label: '礼物'
        },
        {
          value: 'product',
          label: '装扮'
        },
        {
          value: 'debris',
          label: '碎片'
        },
      ],
      menuList1: [],
      menuList2: [],
      menuList3: [],
      optionQuery: {
        page: 1,
        page_size: 50,
        cate_id: 0,
        style_id: 0
      },
      dialogTitle: '新增'
    }
  },
  created() {
    this.initData()
    this.handleGetData()
    this.handleGetProductList()
    this.getChipList()
  },
  methods: {
    handleGetData() {
      getData(this.optionQuery).then(res => {
        
        if (res.code === 200) {
          res.data.data.map(item => {
          
            item.name = item.name + `(${item.price}M豆)`
            
          })
          this.menuList1 = res.data.data
        }
      })
    },
    handleGetProductList() {
      productList(this.optionQuery).then(res => {
        if (res.code === 200) {
          this.menuList2 = res.data.data
        }
      })
    },
    async getChipList(id) {
      const { data, code } = await chipList({
        page: 1,
        perPage: 1000,
        id: id
      })
      if (code === 200) {
        this.menuList3 = data.list
      }

    },
    handleSDelete(row) {
      
      this.$confirm('此操作不可恢复，是否继续删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        prizeDeleted({
          id: row.id
        }).then(res => {
          if (res.code === 200) {
            this.$message({
              type: 'success',
              message: '操作成功'
            })
          }
          this.dialogFormVisible = false
          this.initData()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleSuccess() {
      this.dataForm.title_icon = this.ossLastImgUrl
    },
    handleOnSubmit() {

      this.$refs['form'].validate(valid => {
        if (valid) {

          for (let key in this.formData) {
            this.formData[key] = !this.formData[key] ? 0 : this.formData[key]
          }
          if (this.formData.id) {
            prizeEdit(this.formData).then(res => {
              if (res.code === 200) {
                this.$message({
                  type: 'success',
                  message: '操作成功'
                })
              }
              this.dialogFormVisible = false
              this.initData()
            })
          } else {
            prizeAdd(this.formData).then(res => {
              if (res.code === 200) {
                this.$message({
                  type: 'success',
                  message: '操作成功'
                })
              }
              this.dialogFormVisible = false
              this.initData()
            })
          }

        }
      })
      },
    handleCloseDialog(formName) {
      if (this.$refs[formName]) {
        this.$refs[formName].clearValidate() // 清除整个表单的校验
        this.$refs[formName].resetFields()
      }
      this.formData = {
        reward_type: undefined,
        reward_id: undefined,
        count: undefined,
        level: undefined,
        is_open: undefined,
        id: undefined,
      }
    },

    handleAdd() {
      this.dialogFormVisible = true
      this.isEdit = false
      this.dialogTitle = '新增'
      this.optionQuery.gift_name = undefined
      this.optionQuery.name = undefined
      this.optionQuery.id = undefined
      this.handleGetData()
      this.handleGetProductList()
    },
    handleEdit(row) {
      this.isEdit = true
      this.dialogTitle = '编辑'
      if(row.reward_type === 'gift') {
        this.optionQuery.id = row.reward_id
        this.handleGetData(this.optionQuery)
      }else if(row.reward_type === 'product') {
        this.optionQuery.id = row.reward_id
        this.handleGetProductList(this.optionQuery)
      }else {
        this.getChipList(row.reward_id)
      }
      this.formData = JSON.parse(JSON.stringify(row))
      this.dialogFormVisible = true
    },

    handleReset() {
      this.listQuery = {
        page: 1,
        perPage: 10
      }
    },

    async initData() {
      try {
        const { data } = await listData({
          ...this.listQuery
        })
        this.meta.page = data.meta.page
        this.meta.total = data.meta.total
        this.tableList = data.list
      } catch (e) {
        console.error(e)
      }
    },
    remoteMethod(query) {
      if(query !== '') {
        this.optionQuery.id = undefined
        this.optionQuery.gift_name = query
        this.handleGetData(this.optionQuery)
      }
    },
    remoteMethod2(query) {
      if(query !== '') {
        this.optionQuery.id = undefined
        this.optionQuery.name = query
        this.handleGetProductList(this.optionQuery)
      }
    },
    clear() {
      this.optionQuery = {
        page: 1,
        page_size: 100,
        cate_id: 0,
        style_id: 0
      }
      this.handleGetData(this.optionQuery)
    },
    clear2() {
      this.optionQuery = {
        page: 1,
        page_size: 100,
        cate_id: 0,
        style_id: 0
      }
      this.handleGetProductList(this.optionQuery)
    },
    handleChange() {
      this.formData.reward_id = undefined
      this.formData.count = undefined
    },
    handleInput(val) {
      if(val < 1) {
        this.formData.count = undefined
      }
      if(val.includes('.')) {
        this.formData.count = val.replace('.', '')
      }
    },

  }
}
</script>

<style scoped>
.search {
  padding-left: 70px;
}

.el-input {
  width: 400px;
}

::v-deep .el-upload-list__item {
  transition: none !important;
}

::v-deep.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
</style>
